package com.coolingme.demo.controller;

import com.coolingme.demo.service.DemoService;
import com.coolingme.demo.service.HelloService;
import com.coolingme.springframework.annotation.MeAutowired;
import com.coolingme.springframework.annotation.MeController;
import com.coolingme.springframework.annotation.MeRequestMapping;
import com.coolingme.springframework.annotation.MeRequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 控制层
 *
 * @author wangyue
 * @date 2020/10/23 15:14
 */
@MeController
@MeRequestMapping("/demo")
public class DemoController {

    @MeAutowired
    private DemoService demoService;

    @MeAutowired
    private HelloService helloService;

    @MeRequestMapping("/index")
    public void index() {
        System.out.println("Hello,Spring");
    }

    /**
     * http://127.0.0.1:8080/demo/hello?name=joey
     */
    @MeRequestMapping("/hello*")
    public void hello(HttpServletRequest req, HttpServletResponse resp,
                      @MeRequestParam("name") String name) {
        try {
//            String result = demoService.hello(name);

            String result = helloService.hello(name);
            System.out.println(result);
            String jsonFormat = String.format("{\"result\": \"%s\"}", result);

            resp.setCharacterEncoding("UTF-8");
            resp.setContentType("application/json; charset=utf-8");
            resp.getWriter().write(jsonFormat);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @MeRequestMapping("/add")
    public void add(HttpServletResponse resp,
                    @MeRequestParam("a") String a, @MeRequestParam("b") String b) {
        try {
            Integer addResult = this.demoService.add(a, b);
            String result = a + "+" + b + "=" + addResult;
            System.out.println(result);
            resp.getWriter().write(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @MeRequestMapping("/remove")
    public void remove(@MeRequestParam("id") String id, HttpServletResponse resp) {
        try {
            resp.getWriter().write("remove id:" + id + " success");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
